import React from 'react';
import {connect} from 'react-redux';
import {routerRedux} from 'dva/router';

export function requireAuthentication(Component) {
    @connect(state => ({
        login: state.login,
    }))
    class AuthenticatedComponent extends React.Component {
        state = {
            isLogin: false,
            remote: false
        }

        componentWillMount() {
            this.checkAuth(this.props.isAuthorized, this.props.isCurrSession);
        }

        componentWillReceiveProps(nextProps) {
            this.checkAuth(nextProps.isAuthorized, nextProps.isCurrSession);
        }

        checkAuth(isAuthorized, isCurrSession) {
            if (isCurrSession && isAuthorized) {
                this.setState({
                    isLogin: true,
                });
            } else if (!isAuthorized||(this.state.remote&&this.state.isLogin)) {
                this.props.dispatch(routerRedux.push('/user/login'));
            } else if (!isCurrSession && !this.state.remote) {
                const userObj=JSON.parse(localStorage.getItem("userInfoState"));
                try{
                    const userId=userObj.userInfo.user_id;
                    this.props.dispatch({
                        type: `login/checkToken`,
                        payload: {token: this.props.token,userId:userId},
                    });
                    this.setState({
                        isLogin: false,
                        remote: true
                    });
                }catch (e){
                    this.props.dispatch(routerRedux.push('/user/login'));
                }
            } else {
                this.setState({
                    isLogin: this.props.login.status === 0,
                });
            }
        }

        render() {
            return (
                <div>
                    {this.state.isLogin
                        ? <Component {...this.props}/>
                        : null
                    }
                </div>
            )

        }
    }

    const mapStateToProps = (state) => ({
        token: localStorage.getItem('token'),
        isAuthorized: localStorage.getItem('token') ? true : false,
        isCurrSession: localStorage.getItem('token') == sessionStorage.getItem('token'),
    });

    return connect(mapStateToProps)(AuthenticatedComponent);

}
